// WebSocketService.js
class WebSocketService {
    constructor(url) {
        this.url = url;
        this.ws = null;
        this.onMessageCallback = null;
        this.onOpenCallback = null;
        this.onCloseCallback = null;
        this.onErrorCallback = null;
        this.reconnectInterval = 5000; // 重连间隔时间
        this.shouldReconnect = true; // 是否允许重连
        this.connect(); // 初始连接
    }

    connect() {
        this.ws = new WebSocket(this.url);

        this.ws.onopen = (event) => {
            this.shouldReconnect = true; // 连接成功时允许重连
            if (this.onOpenCallback) {
                this.onOpenCallback(event);
            }
        };

        this.ws.onmessage = (event) => {
            const msg = JSON.parse(event.data);
            if (this.onMessageCallback) {
                this.onMessageCallback(msg);
            }
        };

        this.ws.onclose = (event) => {
            if (this.onCloseCallback) {
                this.onCloseCallback(event);
            }
            // 只有在非手动关闭时才重连
            if (this.shouldReconnect) {
                this.connect()
            }
        };

        this.ws.onerror = (error) => {
            if (this.onErrorCallback) {
                this.onErrorCallback(error);
            }
        };
    }

    sendMessage(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
        } else {
            console.error('WebSocket is not open');
        }
    }

    onMessage(callback) {
        this.onMessageCallback = callback;
    }

    onOpen(callback) {
        this.onOpenCallback = callback;
    }

    onClose(callback) {
        this.onCloseCallback = callback;
    }

    onError(callback) {
        this.onErrorCallback = callback;
    }

    close() {
        this.shouldReconnect = false; // 手动关闭时不重连
        if (this.ws) {
            this.ws.close();
        }
    }
}

export default WebSocketService;
